
import { Level } from "level";
import { catchAwait, } from "utils-lib-js-lite";
import { jsonToString, stringToJson } from "utils-lib-js-lite";
export class LevelDB extends Level {
    constructor(name, options) {
        super(name, options)
    }
    async put<Source = any>(k = "", val: Source, ...rest) {
        val = jsonToString(val) as Source
        const [err, res] = await catchAwait(super.put.call(this, k, val, ...rest))
        if (err) console.log(err);
        return err ? null : res
    }
    async get<Source = any>(k = "", ...rest): Promise<Source> {
        const [err, res] = await catchAwait(super.get.call(this, k, ...rest))
        if (err) console.log(err);
        const _res = err ? null : res
        if (typeof res === 'string') {
            return stringToJson(res) as Source
        }
        return _res
    }
}

export const Answer = new LevelDB('levelDB/answer', { valueEncoding: 'json' })
export const Message = new LevelDB('levelDB/messages', { valueEncoding: 'json' })
export const Event = new LevelDB('levelDB/events', { valueEncoding: 'json' })
